package net.wofly.common.web;

import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.util.ReturnBean;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class BaseController {
    
    /**
     * 登录认证异常
     */
    @ExceptionHandler({ UnauthenticatedException.class, AuthenticationException.class })
    public void authenticationException(HttpServletRequest request, HttpServletResponse response) {
        ReturnBean returnBean = new ReturnBean(-999, "请登录");
        // 输出JSON
        writeJson(returnBean, response);
        //return null;
    }
    
    /**
     * 权限异常
     */
    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    public void authorizationException(HttpServletRequest request, HttpServletResponse response) {
        ReturnBean returnBean = new ReturnBean(-998, "无权限");
        // 输出JSON
        writeJson(returnBean, response);
    }
    
    /**
     * 输出JSON
     *
     * @param response
     * @author SHANHY
     * @create 2017年4月4日
     */
    private void writeJson(ReturnBean returnBean, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(XiNiaoJSON.toJSONString(returnBean));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
}
